﻿using ConfExpert.Forms.Base;
using ConfExpert.Utility;
using DevExpress.Utils;
using DevExpress.XtraBars;
using DevExpress.XtraEditors.Repository;
using DevTeam;
using System;
using System.Data;

namespace ConfExpert.Forms.SatinAlma.YeniYapi
{
    public partial class YeniFatura : XForm
    {
        public YeniFatura()
        {
            InitializeComponent();
        }

        public YeniFatura(int VendorId)
            : this()
        {
            gleGonderen.EditValue = AppSession.Lookups.Vendor.FindByVendorId(VendorId).CariId;
            cmbMalCinsi.Text = "KUMAŞ";
            cmbBirim.Text = "MT";
            gleCustomer.Visible = false;
        }

        public YeniFatura(int dummy, int AlisFaturasiId)
            : this()
        {
            this.AlisFaturasiId = AlisFaturasiId;
            gleCustomer.Visible = dummy > 0;
        }

        private void YeniYuklemeAks_Load(object sender, EventArgs e)
        {
            if (gcMasraf.DataSource == null)
            {
                gvMasraf.SetViewCaption("Masraflar");
                DataTable dtMas = new DataTable();
                dtMas.Columns.Add("MasrafKalemiId", typeof(int));
                dtMas.Columns.Add("Tutar", typeof(double));

                gvMasraf.Init(dtMas);
                gvMasraf.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;
                gvMasraf.OptionsView.ShowAutoFilterRow = false;
                gvMasraf.FormatAsNumber(2, "Tutar");
                gvMasraf.AddSummary("Tutar");
                gvMasraf.BestFitColumns();
                gvMasraf.EnableRowDelete();

                RepositoryItemComboBox riOdemesi = new RepositoryItemComboBox();
                riOdemesi.Items.AddRange(new object[] { "BEDELLİ", "BEDELSİZ" });
                riOdemesi.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
                cmbOdemesi.Properties.Assign(riOdemesi);
                cmbOdemesi.SelectedIndexChanged += cmbOdemesi_SelectedIndexChanged;

                RepositoryItemComboBox riBirimi = new RepositoryItemComboBox();
                riBirimi.Items.AddRange(new object[] { "MT", "ADET" });
                riBirimi.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
                cmbBirim.Properties.Assign(riBirimi);

                gleCustomer.Properties.Assign(RI(Rp.V_Customer));
                gleNakliyeci.Properties.Assign(RI(Rp.Nakliyeci));
                gleGonderen.Properties.Assign(RI(Rp.Cari));

                deFatura.EditValue = DateTime.Now;
                //gleYuklemeSekli.EditValue = 1;

                gleTeslimSekli.Properties.Assign(RI(Rp.TeslimSekliA));
                gleOdemeSekli.Properties.Assign(RI(Rp.PaymentMethodA));
                gleOdemeVadesi.Properties.Assign(RI(Rp.PaymentTerm));
                //gleOdemeSekli.EditValue = 1;

                gleParabirimi.Properties.Assign(RI(Rp.Currency));
                //gleParabirimi.EditValue = 1;

                bbiKaydet.ItemClick += bbiKaydet_ItemClick;
            }


            if (AlisFaturasiId > 0)
            {
                gvMasraf.MakeReadOnly();

                DataSet ds = ExecuteDataSet("GetAlisFaturasiById", AlisFaturasiId);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    DataRow dr = ds.Tables[0].Rows[0];
                    if (dr["AlisFaturasiId"].ToInt() > 0)
                        AlisFaturasiId = dr["AlisFaturasiId"].ToInt();

                    if (dr["TeslimSekliId"].ToInt() > 0)
                        gleTeslimSekli.EditValue = dr["TeslimSekliId"].ToInt();

                    if (dr["CurrencyId"].ToInt() > 0)
                        gleParabirimi.EditValue = dr["CurrencyId"].ToInt();

                    if (dr["FaturaToplami"].ToDecimal(-1) > -1)
                        txtFaturaToplami.EditValue = dr["FaturaToplami"].ToDecimal(-1);

                    txtFaturaToplami.Properties.DisplayFormat.FormatType = FormatType.Numeric;
                    txtFaturaToplami.Properties.DisplayFormat.FormatString = "#,###.##"; //"f2";

                    txtFaturaNo.Text = dr["InvoiceNo"].ToStr();

                    if (dr["InvoiceTarihi"] != DBNull.Value)
                        deFatura.EditValue = dr["InvoiceTarihi"];

                    if (dr["NakliyeciId"].ToInt() > 0)
                        gleNakliyeci.EditValue = dr["NakliyeciId"].ToInt();

                    cmbOdemesi.Text = dr["Odemesi"].ToStr();
                    cmbBirim.Text = dr["Birim2"].ToStr();
                    cmbMalCinsi.Text = dr["MalCinsi"].ToStr();

                    if (dr["PaymentMethodId"].ToInt() > 0)
                        gleOdemeSekli.EditValue = dr["PaymentMethodId"].ToInt();

                    if (dr["PaymentTermId"].ToInt() > 0)
                        gleOdemeVadesi.EditValue = dr["PaymentTermId"].ToInt();

                    if (dr["GrossKg"].ToDecimal(-1) > -1)
                        txtGrossKg.EditValue = dr["GrossKg"].ToDecimal(-1);

                    txtGrossKg.Properties.DisplayFormat.FormatType = FormatType.Numeric;
                    txtGrossKg.Properties.DisplayFormat.FormatString = "#,###.##"; //"f2";

                    //INFO: Aşağıdaki kısım hatalıydı. Orhan Abi'yle konuşup kaldırdım. (KG)
                    //WhoAmI = dr["UserId"].ToInt();

                    if (dr["GonderenId"].ToInt() > 0)
                        gleGonderen.EditValue = dr["GonderenId"].ToInt();

                    if (dr["CustomerId"].ToInt() > 0)
                        gleCustomer.EditValue = dr["CustomerId"].ToInt();

                    gvMasraf.Init(ds.Tables[1]);

                    gvMasraf.DataTable().TableNewRow += YeniFatura_TableNewRow;

                    gvMasraf.MakeColumnInvisible("AlisFaturasiMasrafId", "AlisFaturasiId");
                }
            }

            bbiKaydet.Enabled = cmbOdemesi.SelectedIndex > -1;
            this.Shown += YeniFatura_Shown;
        }

        void YeniFatura_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["AlisFaturasiId"] = AlisFaturasiId;
        }

        void YeniFatura_Shown(object sender, EventArgs e)
        {
            txtFaturaNo.Focus();
        }

        void cmbOdemesi_SelectedIndexChanged(object sender, EventArgs e)
        {
            lblOdemeSekli.Visible = gleOdemeSekli.Visible = lblOdemeVadesi.Visible = gleOdemeVadesi.Visible = cmbOdemesi.Text == "BEDELLİ";
            bbiKaydet.Enabled = cmbOdemesi.SelectedIndex > -1;
        }

        bool chkFaturaNo = false;
        private void check()
        {
            if (AlisFaturasiId > 0)
                chkFaturaNo = true;
            else
            {
                string res = ExecuteScalar("CheckFaturaNo", txtFaturaNo.Text).ToStr();
                if (res != string.Empty)
                {
                    chkFaturaNo = false;
                    ShowErrorMessage("Bu fatura no. daha önce kullanılmış (" + res + "). Aynı numara tekrar kullanılamaz!");
                }
                else
                    chkFaturaNo = true;
            }
        }

        DataTable dtFatura;
        public bool Result = false;
        void bbiKaydet_ItemClick(object sender, ItemClickEventArgs e)
        {
            gvMasraf.EndEditing();

            if (AlisFaturasiId > 0)
            {
                gvMasraf.Update("", "AlisFaturasiMasraf");
            }

            check();
            if (chkFaturaNo)
            {
                //DataSet dsData = ExecDataSet("GetYuklemeAday", 0);
                dtFatura = new DataTable();
                dtFatura.Columns.Add("AlisFaturasiId", typeof(int));
                dtFatura.Columns.Add("TeslimSekliId", typeof(int));
                dtFatura.Columns.Add("FaturaToplami", typeof(decimal));
                dtFatura.Columns.Add("CurrencyId", typeof(int));
                dtFatura.Columns.Add("FaturaNo", typeof(string));
                dtFatura.Columns.Add("IrsaliyeNo", typeof(string));
                dtFatura.Columns.Add("FaturaTarihi", typeof(DateTime));
                dtFatura.Columns.Add("IrsaliyeTarihi", typeof(DateTime));
                dtFatura.Columns.Add("NakliyeciId", typeof(int));
                dtFatura.Columns.Add("Odemesi", typeof(string));
                dtFatura.Columns.Add("PaymentTermId", typeof(int));
                dtFatura.Columns.Add("PaymentMethodId", typeof(int));
                dtFatura.Columns.Add("GrossKg", typeof(decimal));
                dtFatura.Columns.Add("MalCinsi", typeof(string));
                dtFatura.Columns.Add("Birim2", typeof(string));
                dtFatura.Columns.Add("GonderenId", typeof(int));
                dtFatura.Columns.Add("CustomerId", typeof(int));
                dtFatura.Columns.Add("UserId", typeof(int));

                dtFatura.AddAutoIncrementalColumn("YuklemeId");

                DataRow dr = dtFatura.NewRow();

                if (AlisFaturasiId > 0)
                    dr["AlisFaturasiId"] = AlisFaturasiId;

                if (gleTeslimSekli.EditValue.ToDecimal(-1) > -1)
                    dr["TeslimSekliId"] = gleTeslimSekli.EditValue.ToInt(-1);

                if (gleParabirimi.EditValue.ToDecimal(-1) > -1)
                    dr["CurrencyId"] = gleParabirimi.EditValue.ToInt(-1);

                if (txtFaturaToplami.EditValue.ToDecimal(-1) > -1)
                    dr["FaturaToplami"] = txtFaturaToplami.EditValue.ToDecimal(-1);

                dr["FaturaNo"] = txtFaturaNo.Text;

                if (deFatura.EditValue != null)
                    dr["FaturaTarihi"] = deFatura.EditValue;

                if (gleNakliyeci.EditValue.ToDecimal(-1) > -1)
                    dr["NakliyeciId"] = gleNakliyeci.EditValue.ToInt(-1);

                dr["Odemesi"] = cmbOdemesi.Text;
                dr["Birim2"] = cmbBirim.Text;
                dr["MalCinsi"] = cmbMalCinsi.Text;

                if (gleOdemeSekli.EditValue.ToDecimal(-1) > -1)
                    dr["PaymentMethodId"] = gleOdemeSekli.EditValue.ToInt(-1);

                if (gleOdemeVadesi.EditValue.ToDecimal(-1) > -1)
                    dr["PaymentTermId"] = gleOdemeVadesi.EditValue.ToInt(-1);

                if (txtGrossKg.EditValue.ToDecimal(-1) > -1)
                    dr["GrossKg"] = txtGrossKg.EditValue.ToDecimal();

                dr["UserId"] = WhoAmI;

                if (gleGonderen.EditValue.ToInt() > -1)
                    dr["GonderenId"] = gleGonderen.EditValue.ToInt();

                if (gleCustomer.EditValue.ToInt() > -1)
                    dr["CustomerId"] = gleCustomer.EditValue.ToInt();

                dtFatura.Rows.Add(dr);

                string xml1 = dtFatura.Serialize();
                string xml2 = gvMasraf.Serialize();
                AlisFaturasiId = Session.DataManager.ExecuteScalar("InsFatura", xml1, xml2).ToInt();

                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                //XtraMessageBox.Show("Fatura bilgisi başarıyla kaydedildi.", "Onay", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);

            }
        }
        public int AlisFaturasiId;
    }
}
